import OSS from 'ali-oss';
import { getOSSConfig, validateOSSConfig, getUploadConfig, getPathConfig } from '../config/oss.config';

// 阿里云OSS配置
interface OSSConfig {
  region: string;
  accessKeyId: string;
  accessKeySecret: string;
  bucket: string;
  endpoint?: string;
  secure?: boolean;
  timeout?: number;
}

// 创建OSS客户端
let ossClient: OSS | null = null;

export const initOSS = (config?: Partial<OSSConfig>) => {
  const defaultConfig = getOSSConfig();
  const finalConfig = { ...defaultConfig, ...config };
  
  try {
    // 验证配置
    validateOSSConfig(finalConfig);
    
    ossClient = new OSS({
      region: finalConfig.region,
      accessKeyId: finalConfig.accessKeyId,
      accessKeySecret: finalConfig.accessKeySecret,
      bucket: finalConfig.bucket,
      endpoint: finalConfig.endpoint,
      secure: finalConfig.secure ?? true,
      timeout: finalConfig.timeout ?? 60000,
    });
    
    console.log('OSS客户端初始化成功');
    return ossClient;
  } catch (error) {
    console.error('OSS客户端初始化失败:', error);
    throw error;
  }
};

// 获取OSS客户端实例
export const getOSSClient = () => {
  if (!ossClient) {
    throw new Error('OSS客户端未初始化，请先调用initOSS()');
  }
  return ossClient;
};

// 生成唯一的文件名
export const generateFileName = (originalName: string): string => {
  const pathConfig = getPathConfig();
  const timestamp = Date.now();
  const random = Math.random().toString(36).substring(2, 15);
  const extension = originalName.split('.').pop();
  return `${pathConfig.imagePrefix}${timestamp}_${random}.${extension}`;
};

// 验证文件
export const validateFile = (file: File, skipTypeCheck: boolean = false): { valid: boolean; message?: string } => {
  const uploadConfig = getUploadConfig();
  
  // 检查文件大小
  if (file.size > uploadConfig.maxFileSize) {
    return {
      valid: false,
      message: `文件大小不能超过${uploadConfig.maxFileSize / 1024 / 1024}MB`
    };
  }
  
  // 检查文件类型（如果允许所有类型或跳过类型检查，则不验证）
  if (!skipTypeCheck && uploadConfig.allowedTypes[0] !== '*/*') {
    if (!uploadConfig.allowedTypes.includes(file.type)) {
      return {
        valid: false,
        message: `不支持的文件类型: ${file.type}`
      };
    }
  }
  
  return { valid: true };
};

// 上传文件到OSS
export const uploadToOSS = async (file: File, customPath?: string, skipTypeCheck: boolean = false): Promise<string> => {
  try {
    // 验证文件
    const validation = validateFile(file, skipTypeCheck);
    if (!validation.valid) {
      throw new Error(validation.message);
    }
    
    const client = getOSSClient();
    const fileName = customPath || generateFileName(file.name);
    
    console.log('开始上传文件到OSS:', fileName, '文件大小:', file.size);
    
    // 上传文件
    const result = await client.put(fileName, file);
    
    console.log('文件上传成功:', result.url);
    
    // 返回文件的访问URL
    return result.url;
  } catch (error) {
    console.error('文件上传到OSS失败:', error);
    throw error;
  }
};

// 从OSS删除文件
export const deleteFromOSS = async (fileUrl: string): Promise<boolean> => {
  try {
    const client = getOSSClient();
    
    // 从URL中提取文件名
    const url = new URL(fileUrl);
    const fileName = url.pathname.substring(1); // 移除开头的斜杠
    
    console.log('开始删除OSS文件:', fileName);
    
    await client.delete(fileName);
    
    console.log('文件删除成功:', fileName);
    return true;
  } catch (error) {
    console.error('从OSS删除文件失败:', error);
    return false;
  }
};

// 检查OSS连接
export const checkOSSConnection = async (): Promise<boolean> => {
  try {
    const client = getOSSClient();
    await client.list({ 'max-keys': 1 });
    return true;
  } catch (error) {
    console.error('OSS连接检查失败:', error);
    return false;
  }
};

// 获取文件访问URL（带签名）
export const getSignedUrl = async (fileName: string, expires: number = 3600): Promise<string> => {
  try {
    const client = getOSSClient();
    const url = await client.signatureUrl(fileName, { expires });
    return url;
  } catch (error) {
    console.error('获取签名URL失败:', error);
    throw error;
  }
};

// 批量上传文件
export const uploadMultipleToOSS = async (files: File[]): Promise<string[]> => {
  const uploadPromises = files.map(file => uploadToOSS(file));
  return Promise.all(uploadPromises);
};

// 初始化OSS（在应用启动时调用）
export const initializeOSS = () => {
  return initOSS();
}; 